package com.bookstore.service;

import com.bookstore.dao.UserDao;
import com.bookstore.exception.UserException;
import com.bookstore.model.User;
import com.bookstore.utils.SendJMail;

import java.sql.SQLException;

public class UserService {
    //去掉用Dao与数据库做交互
    UserDao userDao = new UserDao();
    public void register(User user) throws UserException {
        try {
            //调用Dao添加用户
            userDao.addUser(user);
            String link = "http://localhost:8080/bookstore/activate?ActivateCode="+user.getActiveCode();
            String html = "<a href=\""+link+"\">点击激活</a>";
            System.out.println(html);
            SendJMail.sendMail(user.getEmail(),html);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new UserException("用户注册失败，用户名重复！");
        }
    }
    public void activeUser (String ActivateCode)throws UserException{
        try {
            //1.查询激活码的用户是否存在
            //在try块里尽量不要写throw，否则会在catch中被获取，而不是在外部定义函数中throw出来
            User user = userDao.findUserbyActivateCode(ActivateCode);
            if(user==null){
                throw new UserException("非法激活，用户不存在！");
            }
            if (user!=null&&user.getState()==1){
                throw new UserException("用户已经激活过了，请不要重复激活！");
            }
            //更新state激活用户
            userDao.updateState(ActivateCode);
        } catch (SQLException e) {
//            e.printStackTrace();
            throw new UserException("激活失败");
        }

    }
}
